//
//  CYPostedOnlineDetailTVC.m
//  CreditAddressBook
//
//  Created by LE on 16/1/5.
//  Copyright © 2016年 Lee. All rights reserved.
//

#import "CYPostedOnlineDetailTVC.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "CYNetworkCollectRecord.h"
#import "UIImageView+WebCache.h"
#import "CYCreditTool.h"
#import "MBProgressHUD+MJ.h"
#import "CYAppealView.h"
#import "LEPhotoBrowserTool.h"

@interface CYPostedOnlineDetailTVC ()
@property (weak, nonatomic) IBOutlet UILabel *titleL;
@property (weak, nonatomic) IBOutlet UILabel *pubPersonL;
@property (weak, nonatomic) IBOutlet UILabel *pubTime;
@property (weak, nonatomic) IBOutlet UIImageView *iconIV;

@property (weak, nonatomic) IBOutlet UILabel *nameL;
@property (weak, nonatomic) IBOutlet UILabel *sexL;
@property (weak, nonatomic) IBOutlet UILabel *phoneL;
@property (weak, nonatomic) IBOutlet UILabel *idCardL;
@property (weak, nonatomic) IBOutlet UILabel *areaL;

@property (weak, nonatomic) IBOutlet UILabel *descriptionL;

@property (weak, nonatomic) IBOutlet UITableViewCell *photoCell;
@property (weak, nonatomic) IBOutlet UITableViewCell *descriptionCell;
@property (weak, nonatomic) IBOutlet UITableViewCell *persionInfoCell;
@property (weak, nonatomic) IBOutlet UITableViewCell *titleCell;

@property(nonatomic, weak) UIView *photoView;
@property(nonatomic, strong) CYNetworkCollectRecord *showRecord;

@property(nonatomic, copy) CYLoadCompletion loadCompletionBlock;
@end

@implementation CYPostedOnlineDetailTVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadData];
    self.automaticallyAdjustsScrollViewInsets = NO;
}
//网络请求
- (void)loadData {
    [MBProgressHUD showMessage:nil toView:self.view];
    [CYCreditTool getAuditNetworkCollectRecordsByIdWithParam:@{@"id": self.record.recordId} success:^(CYNetworkCollectRecord *record) {
        [MBProgressHUD hideHUDForView:self.view];
        [self initData:record];
        self.showRecord = record;
        [self.tableView reloadData];
    } failure:^(NSString *message, NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        if (message) {
            [MBProgressHUD showError:message];
        } else if (error) {
            [MBProgressHUD showError:@"服务器连接错误"];
        }
    }];
}

- (void)initData:(CYNetworkCollectRecord *)record {
    //title
    self.titleL.text = record.title;
    if (record.publishHeadPic && !record.publishHeadPic.isEmpty) {
        [self.iconIV sd_setImageWithURL:CYURLWithUserService(record.publishHeadPic) placeholderImage:[UIImage imageNamed:@"ic_contact_info_header"]];
    }
    self.pubPersonL.text = CYStringFormat(@"发布人：%@", record.publishUserName);
    self.pubTime.text = CYStringFormat(@"发布时间：%@", [CYCreditTool timewithLongLongValue:record.createTime.longLongValue  formatter:CYTimeFormatYMDHmsType]);
    //违约人
    self.nameL.text = CYStringFormat(@"违约人：%@", record.name);;
    if (record.sex.intValue == 0) {
        self.sexL.text = @"男";
    }else if (record.sex.intValue == 1){
        self.sexL.text = @"女";
    }
    
   // self.sexL.text = CYStringFormat(@"性别：%@", [CYCreditTool idCardInfo:record.certificateNo][@"sex"]);
    if (record.phone && !record.phone.isEmpty) {
        self.phoneL.text = CYStringFormat(@"手机号：%@", record.phone);
    } else {
        self.phoneL.text = @"手机号：--";
    }
    if (record.certificateNo && !record.certificateNo.isEmpty) {
        self.idCardL.text = CYStringFormat(@"身份证号：%@", record.certificateNo);
    } else {
        self.idCardL.text = @"身份证号：--";
    }
    self.areaL.text = CYStringFormat(@"所在地区：%@-%@", record.province, record.city);
    //违约描述
    if (record.defaultContent) {
        self.descriptionL.text = record.defaultContent;
    } else {
        self.descriptionL.text = @" ";
    }
    //证据照片
    UIView *photoView = [record picAddressListView];
    [self.photoCell.contentView addSubview:photoView];
    [photoView autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsMake(8, 8, 8, 8)];
    self.photoView = photoView;
    //创建照片浏览
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(photoBrowser:)];
    [photoView addGestureRecognizer:tap];
    
    if (self.loadCompletionBlock) {
        self.loadCompletionBlock(record);
        self.loadCompletionBlock = nil;
    }
}
/**
 *  图片浏览器
 */
- (void)photoBrowser:(UITapGestureRecognizer *)tap {
    NSArray *urls = self.showRecord.picAddressList;
    MWPhoto *photo = nil;
    NSMutableArray *photos = [NSMutableArray array];
    for (NSString *url in urls) {
        photo = [MWPhoto photoWithURL:CYURLWithService(url)];
//        photo.caption = @"title";
        [photos addObject:photo];
    }
    [LEPhotoBrowserTool showPhotoBrowserWithController:self photos:photos];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.showRecord) {
        return 4;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return .1;
    }
    return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return .1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return self.titleCell.height;
    } else if (indexPath.section == 1) {
        return self.persionInfoCell.height;
    } else if (indexPath.section == 2) {
        return [tableView fd_heightForCell:self.descriptionCell configuration:nil] + 80;
    }
    return [tableView fd_heightForCell:self.photoCell configuration:nil] + 200;
}

#pragma mark - 
- (void)loadCompletion:(CYLoadCompletion)completion {
    self.loadCompletionBlock = [completion copy];
}

- (UIImage *)cropTable {
    return [self getFullImage:self.tableView];
}

- (UIImage *)getFullImage:(UITableView *)tableView {
    NSInteger sectionIndex = 2;
    //t来保存整张图的高度
    int t = 0;
    for (int i = 0; i < [self tableView:tableView numberOfRowsInSection:sectionIndex]; ++i) {
        NSIndexPath *path = [NSIndexPath indexPathForRow:i inSection:sectionIndex];
        t += [self tableView:tableView heightForRowAtIndexPath:path];
    }
    //开始绘图
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(tableView.width, t), NO, [UIScreen mainScreen].scale);
//    UIGraphicsBeginImageContext(CGSizeMake(320, t));
    //获取当前图形上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    //保存上一个cell绘制时候的纵向偏移
    float lasty = .0;
    //保存当前总共绘制的高度
    float height = .0;
//    UIView *sectionView = [self tableView:tableView viewForHeaderInSection:sectionIndex];
//    CGFloat sectionH = [self tableView:tableView heightForHeaderInSection:sectionIndex];
    //使用循环创建tableviewcell绘制在图形上下文之上
    for (int i = 0; i < [self tableView:tableView numberOfRowsInSection:sectionIndex]; ++i) {
        //绘制第i个cell的时候需要下移前面所有cell高度的和
        CGContextTranslateCTM(context,.0,-lasty);
        
        NSIndexPath *path = [NSIndexPath indexPathForRow:i inSection:sectionIndex];
        //获取cell
        UITableViewCell *Cell = [tableView cellForRowAtIndexPath:path];
        if (Cell == nil) {
            Cell = [self tableView:tableView cellForRowAtIndexPath:path];
        }
        
        height += [self tableView:tableView heightForRowAtIndexPath:path];
        
        float y = height - [self tableView:tableView heightForRowAtIndexPath:path];
        //绘图偏移移回最顶部
        CGContextTranslateCTM(context,.0,y);
        //绘制
        [Cell.layer renderInContext:context];
        
        lasty = y;
    }
    //结束绘图
    CGImageRef imageMasked = CGBitmapContextCreateImage(context);
    UIImage *fullimage = [UIImage imageWithCGImage:imageMasked];
    UIGraphicsEndImageContext();
    return fullimage;
}
@end
